#include <core/mutex.h>

namespace Core
{

ThreadMutex::ThreadMutex(const String& name) : m_name(name), m_mutex(0)
{
    m_mutex = CreateMutexW(0, false, m_name.c_str());
}

bool ThreadMutex::lock(ULong ms)
{
    DWORD state = WaitForSingleObject(m_mutex, ms);
    switch(state)
    {
    //fall through
    case WAIT_TIMEOUT:
    case WAIT_FAILED:
        return false;
    }
    return true;
}

bool ThreadMutex::lock()
{
    return lock(INFINITE);
}


bool ThreadMutex::tryLock()
{
    return lock(0L);
}

void ThreadMutex::unlock()
{
    if (m_mutex)
    {
        ReleaseMutex(m_mutex);
    }
}

ThreadMutex::~ThreadMutex()
{
    if (m_mutex != INVALID_HANDLE_VALUE)
    {
        CloseHandle(m_mutex);
    }
    m_mutex = 0;
}

}